﻿using System;
using System.Windows;
using System.Windows.Controls;
using SilverlightProgressFeedback.ServiceReference1;

namespace SilverlightProgressFeedback.Views
{
    public partial class ProgressFeedbackWindow : ChildWindow
    {                
        public ProgressFeedbackWindow(string caption)
            : this()
        {
            Title = caption;
        }

        public ProgressFeedbackWindow()
        {
            InitializeComponent();
            ProgressFeedbackKey = Guid.NewGuid();
            FeedbackWait = 500;
        }

        public Guid ProgressFeedbackKey { get; private set; }
        public int FeedbackWait { get; set; }
        public bool Aborted { get; private set; }

        public void ProcessDone()
        {
            Close();
        }

        private void CancelButtonClick(object sender, RoutedEventArgs e)
        {
            Service1Client client = new Service1Client();
            client.AbortProcessAsync(ProgressFeedbackKey);
            Aborted = true;
        }

        private void RequestFeedback()
        {
            if (Visibility == Visibility.Visible)
            {
                Service1Client client = new Service1Client();

                client.GetProcessInfoCompleted +=
                    (a, b) =>
                    {
                        if (Visibility == Visibility.Visible)
                        {
                            Description.Text = b.Result.Description;
                            Messages.Text = string.Join(Environment.NewLine, b.Result.Messages);
                            RequestFeedback();
                        }
                    };

                client.GetProcessInfoAsync(ProgressFeedbackKey, FeedbackWait);
            }
        }

        private void ChildWindowGotFocus(object sender, RoutedEventArgs e)
        {
            GotFocus -= ChildWindowGotFocus;
            RequestFeedback();
        }
    }
}

